{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% load mptt_tags %}

{% block title %}{{ post.title }}{% endblock %}

{% block content %}
<div class="container">
    <div class="row">
        <div class="col-md-10 offset-md-1 bg-white p-4">
        <div class="media">
    <div class="media-body">
        <h1 class="text-weight-bold">{{ post.title }}</h1>
        <a class="text-decoration-none" href="{% url 'blog:user_posts' post.user.username %}">
            <img src="{{ post.user.profile.avatar.url }}" width="60" height="60" class="mr-1 rounded-circle" alt="个人头像">
        </a>
        <small class="mt-1 text-muted">
            <span>
                <a class="text-decoration-none font-weight-bold text-secondary" href="{% url 'blog:user_posts' username=post.user.username %}">{{ post.user.username }}</a>
            发布于 <time datetime="{{ post.date_created | date:'Y-m-d' }}">{{ post.date_created | date:'Y-m-d' }}</time>
               阅读({{ post.num_views }})
                评论({{ post.num_comments }})
            </span>

            {% if post.user == request.user %}
            <a class="bg-info text-white text-decoration-none text-weight-bold p-1" href="{{ post.get_edit_url }}">编辑文章</a> ·
            <a class="bg-danger text-white text-decoration-none text-weight-bold p-1" href="{{ post.get_delete_url }}">删除文章</a>
            {% endif %}
        </small>
        <p class="text-justify mt-4 p-2">{{ post.content|safe }}</p>

        <!--点赞-->
         <div class="d-flex justify-content-center m-3">
            <button type="button" class="btn btn-outline-danger like-btn">点赞
                <i class="fa fa-heart-o" aria-hidden="true"></i><span class="ml-1">{{ post.num_likes }}</span>
            </button>
         </div>

        {% if request.user.is_authenticated %}
        <!--评论-->
        <form method="POST">
            {% csrf_token %}
            <fieldset class="form-group mb-0">
                {{ form | crispy }}
            </fieldset>
            <div class="form-group d-flex justify-content-end mt-0">
                <button class="commenting-btn btn btn-outline-info" type="submit">发布</button>
            </div>
        </form>
        {% else %}
        <p><a class="text-decoration-none" href="{% url 'account:login' %}?next={{ post.get_absolute_url }}">登录评论</a></p>
        {% endif %}
    </div>

</div>
        <hr>
        <a name="comments"></a>
        {% if comments %}
        <h4>共<span id="comment-count">{{ comments.count }}</span>条评论</h4>
        <div class="comments">
                                 {% recursetree comments %}
                                 {% with comment=node %}
                                 <div class="media border-bottom p-3">
                                 <img src="{{ comment.user.profile.avatar.url }}" class="rounded-circle mr-3" width="60" height="60" alt="个人头像">
                                 <div class="media-body">
                                 <h5 class="mt-0">{{ comment.user.username }}</h5>
                                 <small class="text-muted d-block mb-2">{{ comment.date_created|date:"Y.m.d H:i" }}</small>
                                 <!--如果是回复评论，显示回复人用户名-->
                                 {% if comment.reply_to %}
                                 <a class="text-muted" href="{% url 'blog:user_posts' comment.reply_to.username %}">@{{ comment.reply_to.username }}</a>
                                 {% endif %}
                                 {{ comment.content }}

                                 <div class="d-flex justify-content-end">

                                 <!--显示删除按钮-->
                                 {% ifequal request.user comment.user %}
                                 <small>
                                 <a href="#" class="text-danger comment-delete-btn mr-2" id="{{ comment.slug }}">删除</a>
                                 </small>
                                 {% endifequal %}

                                 <!--显示回复按钮-->
                                 {% if user.is_authenticated %}
                                 <small>
                                 <a href="#" class="text-seondary comment-reply-btn" data-toggle="modal" data-target="#replyModal-{{ comment.slug }}">
                                 回复
                                 </a>
                                 </small>
                                 {% else %}
                                 <small>
                                 <a href="{% url 'account:login' %}?next={{ post.get_absolute_url }}" class="text-seondary">
                                 回复
                                 </a>
                                 </small>
                                 {% endif %}
                                 </div>

                                 <!-- Modal -->
                                 <div class="modal fade" id="replyModal-{{ comment.slug }}" tabindex="-1" role="dialog" aria-labelledby="replyModalLabel"
                                 aria-hidden="true">
                                 <div class="modal-dialog" role="document">
                                 <div class="modal-content">
                                 <div class="modal-header">
                                 <h5 class="modal-title" id="exampleModalLabel">回复: {{ comment.user.username }}</h5>
                                 <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                 <span aria-hidden="true">&times;</span>
                                 </button>
                                 </div>
                                 <div class="modal-body">
                                 <form method="POST" novalidate>
                                 {% csrf_token %}
                                 {{ form | crispy }}
                                 <fieldset class="form-group mb-0">
                                 <input type="hidden" name="parent" value="{{ comment.slug }}">
                                 </fieldset>
                                 <div class="form-group d-flex justify-content-end mt-0">
                                 <button type="button" class="btn btn-info mr-2" data-dismiss="modal">关闭
                                 </button>
                                 <button class="btn btn-outline-info reply-btn" data-dismiss="modal"
                                 type="submit">回复
                                 </button>
                                 </div>
                                 </form>
                                 </div>
                                 </div>
                                 </div>
                                 </div>

                                 <!--显示回复评论-->
                                 {% if not comment.is_leaf_node %}
                                 <div class="children-{{ comment.slug }}">
                                 {{ children }}
                                 </div>
                                 {% endif %}

                                 </div>
                                 </div>
                                 {% endwith %}
                                 {% endrecursetree %}
                                 </div>
        {% endif %}
        </div>
    </div>
</div>
{% endblock %}

{% block js %}
<script>
    $(document).ready(function() {
        // 提交评论
        $('.commenting-btn').click(function (e) {
            e.preventDefault();
            var content = $("textarea[id='id_content']").val();
            // ajax
            $.ajax({
                url: '/comment/new/',
                method: 'POST',
                dataType: 'json',
                data: JSON.stringify({content: content, post_slug: '{{ post.slug }}'}),
                headers: {
                    'X-CSRFTOKEN': getCookie('csrftoken'),
                    'Content-Type': 'application/json',
                },
                success: function(data) {
                    if (data.code === 0) {
                        window.location.reload();

                        // 清空评论输入框
                        $('#id_content').val('');
                    }
                }
            });
        })
        /*
        Jquery 动态添加删除元素 用js添加的元素无法删除问题
        https://www.cnblogs.com/yisouhou/p/3853602.html
        */


        // 删除评论
        $('.comment-delete-btn').click(function (e) {
            e.preventDefault();
            var slug = e.target.id;
            var current_comment = $(this).parent().parent();

            // ajax
            $.ajax({
                url: `/comment/${slug}/delete/`,
                method: 'POST',
                dataType: 'json',
                headers: {
                    'X-CSRFTOKEN': getCookie('csrftoken'),
                    'Content-Type': 'application/json'
                },
                success: function(data, textSuccess) {
                    if (textSuccess === 'success' && data['code'] === 0) {
                        current_comment.remove();
                        // 更新评论数
                        var count = parseInt($('#comment-count').text());
                        count--;
                        $('#comment-count').html(count);
                        // 重新加载页面 - 改善为不加载？？？
                        window.location.reload();
                    } else {
                        // 处理错误！！！
                    }
                }
            });
        });

        // 回复评论
        $('.reply-btn').click(function (e) {
            e.preventDefault();

            content = $(this).parent().prev().prev().find('textarea').val();

            // 要找相对位置的元素的值
            var parent_comment_slug = $(this).parent().prev().find('input').val();

            // ajax
            $.ajax({
                url: '/comment/new/',
                method: 'POST',
                dataType: 'json',
                data: JSON.stringify({content: content, post_slug: '{{ post.slug }}', parent_comment_slug: parent_comment_slug}),
                headers: {
                    'X-CSRFTOKEN': getCookie('csrftoken'),
                    'Content-Type': 'application/json',
                },
                success: function(data) {
                    if (data.code === 0) { // 回复成功
                        window.location.reload();
                    }
                }
            });
        });


        // 点赞

        $('.like-btn').click(function(e) {
            var like_count = $('.like-btn span').text();


            $.post(
                '/post/{{ post.slug }}/likes/',
                function(data) {
                    if (data.code === 0) {
                        like_count++;
                        $('.like-btn span').text(like_count);

                        $('.like-btn i').removeClass('fa-heart-o').addClass('fa-heart');
                    } else {
                        // 出错
                        if (data.errors) {
                            alert(data.errors);
                        }
                    }
                }
            );
        });
    })
</script>
{% endblock %}
